//
//  flickrFirstGrabber.m
//  citipad
//
//  Created by Chih Yuan Liu on 3/17/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "flickrFirstGrabber.h"
#import "CTPFlickrFirstFetcher.h"

@implementation flickrFirstGrabber

-(id)initWithImageView:(UIImageView*)imageview{
	if(self = [super init]){
		holder = imageview;
		stop = NO;
	}
	return self;
}

-(void) requireStop{
	stop = YES;
}

-(void) grabImage:(NSString*) imagekey fetchkey:(NSString*)fetchkey{
	NSString *filename = imagekey;
	uniquePath = [NSTemporaryDirectory() stringByAppendingPathComponent: filename];
	
	if([[NSFileManager defaultManager] fileExistsAtPath: uniquePath]){
		UIImage *img = [UIImage imageWithContentsOfFile:uniquePath];
		[holder setImage:img];
		NSLog(@"hit:%@", uniquePath);
	}else {
		CTPFlickrFirstFetcher *fetcher = [[CTPFlickrFirstFetcher alloc] init];
		fetcher.delegate = self;
		[fetcher getDataFromCtp:fetchkey];
	}
	//NSLog(@"%@", uniquePath);
}

- (void)flickrFirstFetcherBegin:(CTPFlickrFirstFetcher*)sender{}
- (void)flickrFirstFetcherEnd:(CTPFlickrFirstFetcher*)sender{}
- (void)flickrFirstFetcherSucceeded:(CTPFlickrFirstFetcher*)sender data:(NSData*)data{
	UIImage *image = [UIImage imageWithData:data];
	NSLog(@"holder: %@", holder);
	if(stop==NO && holder!=nil){
		[holder setImage:image];
	}
	//NSLog(@"%@", uniquePath);
	//[UIImagePNGRepresentation(image) writeToFile:uniquePath atomically:YES];
	
}
- (void)flickrFirstFetcherFailed:(CTPFlickrFirstFetcher*)sender{}

@end
